<template>
  <el-card shadow="never">
    <el-scrollbar  height="calc(100vh - 200px)">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px">
          <span style="font-size: 18px;margin-left: 7px">任务配置</span>
        <div style="display: flex; gap: 5px">
          <el-button type="primary" @click="clickSetEdit">保存</el-button>
          <el-button type="info" @click="clickSetting">导入预设配置</el-button>
        </div>
      </div>
      <el-form :model="configForm"  :rules="rulesConfig" ref="ConfigRef" label-width="95px" >
        <el-form-item label="运行模式：" prop="distributed_mode">
          <el-tag :type="configForm.distributed_mode === 'distributed' ? 'warning' : 'info'">
            {{ configForm.distributed_mode === 'distributed' ? '分布式模式' : '单机模式' }}
          </el-tag>
          <div v-if="configForm.distributed_mode === 'single'" class="tip-box info" style="margin-top: 5px;">
            <el-icon><InfoFilled /></el-icon>
            <span>单机模式下无需选择服务器，系统将自动分配本机资源。</span>
          </div>
        </el-form-item>
        <!-- 分布式模式下的服务器配置 -->
        <el-form-item v-if="configForm.distributed_mode === 'distributed'" style="margin-top: 15px;margin-bottom: 15px" label="运行机器：" prop="resource">
          <el-radio-group v-model="configForm.resource" @change="onResourceChange">
            <el-radio label="10">默认
              <el-tooltip content="使用任务初始配置的主服务器和工作服务器" :enterable="false" placement="top">
                <i class="el-icon-question" style="color: #909399; font-size: 16px;"></i>
              </el-tooltip>
            </el-radio>
            <el-radio label="20">自定义
              <el-tooltip content="手动选择主服务器和工作服务器" :enterable="false" placement="top">
                <i class="el-icon-question" style="color: #909399; font-size: 16px;"></i>
              </el-tooltip>
            </el-radio>
          </el-radio-group>
          <div v-if="configForm.resource === '10'" class="tip-box info" style="margin-top: 5px;">
            <el-icon><InfoFilled /></el-icon>
            <span>将使用任务创建时配置的主服务器和工作服务器。</span>
          </div>
          <div v-if="configForm.resource === '20'" class="tip-box warning" style="margin-top: 5px;">
            <el-icon><InfoFilled /></el-icon>
            <span>请手动选择主服务器和工作服务器，确保资源可用。</span>
          </div>
        </el-form-item>
        <!-- 自定义服务器选择 -->
        <div v-if="configForm.distributed_mode === 'distributed' && configForm.resource === '20'">
          <el-form-item label="主服务机：" prop="master_server">
            <el-select v-model="configForm.master_server" placeholder="请选择主服务器" style="width: 100%">
              <el-option v-for="server in serverData" :key="server.id" :label="`${server.name} (${server.host_ip})`" :value="server.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="工作机：" prop="worker_servers">
            <el-select v-model="configForm.worker_servers" multiple placeholder="请选择工作服务器" style="width: 100%">
              <el-option v-for="server in serverData" :key="server.id" :label="`${server.name} (${server.host_ip})`" :value="server.id" />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="任务类型：" prop="taskType">
          {{ taskTypeMap[configForm.taskType] || configForm.taskType}}
        </el-form-item>
        <el-form-item prop="name" label="配置名称：" >
          <el-input v-model="configForm.name" placeholder="请输入配置名称"></el-input>
        </el-form-item>
        <el-form-item v-if="configForm.taskType==='20'" label="时间配置：" prop="rule">
          <el-popover
            v-model:visible="cronVisible"
            placement="bottom-start"
            width="30">
            <template #reference>
              <el-input
                v-model="configForm.rule"
                clearable
                readonly
                placeholder="请选择定时任务时间配置"
                @click="cronFun"
              />
            </template>
            <timerTaskCron
              :runTimeStr="configForm.rule"
              @closeTime="closeRunTimeCron"
              @runTime="runTimeCron"
            >
              </timerTaskCron>
          </el-popover>
        </el-form-item>
        <el-form-item prop="logMode" label="日志模式：" >
          <el-select  v-model="selectedLogMode" placeholder="请选择日志模式" style="width: 100%">
            <el-option label="关闭" value=0></el-option>
            <el-option label="开启-全部日志" value=10></el-option>
            <el-option label="开启-仅成功日志" value=20></el-option>
            <el-option label="开启-仅失败日志" value=30></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="控制模式：" prop="control">
          <el-select v-model="selectControlMode" placeholder="请选择控制模式" style="width: 100%">
            <el-option label="集合模式" value=10></el-option>
            <el-option label="单独模式" value=20></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="压测模式：" prop="pressureMode">
          <el-select v-model="selectPressureMode" placeholder="请选择压测模式" style="width: 100%">
            <el-option label="并发模式" value='10'></el-option>
            <el-option label="阶梯模式" value='20'></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时长单位：" prop="pressureMode">
          <el-select v-model="configForm.timeUnit" placeholder="请选择时长单位" style="width: 100%">
            <el-option label="s" value="s"></el-option>
            <el-option label="m" value="m"></el-option>
            <el-option label="h" value="h"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="思考时间：" prop="thinkTime">
                  <el-select v-model="selectTimeType" placeholder="请选择时间类型" style="width: 100%;margin-bottom: 10px">
                    <el-option label="固定" value='10'></el-option>
                    <el-option label="随机" value='20'></el-option>
                  </el-select>
                  <span v-if="configForm.thinkTimeType === '20'">
                    <el-input-number
                      v-model="configForm.thinkTime[0]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px"
                    />
                    <span style="margin-right: 5px;margin-left: 5px">-</span>
                    <el-input-number
                      v-model="configForm.thinkTime[1]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px"
                    />
                  </span>
                  <span v-else>
                    <el-input-number
                      v-model="configForm.thinkTime[0]"
                      :min="0"
                      :max="999"
                      size="small"
                      controls-position="right"
                      @change="handleChange"
                      style="width: 90px"
                    />
                  </span>
                </el-form-item>
        <el-card v-if="configForm.pressureMode==='10'" style="background-color: #f5f7f9" class="card" shadow="always">
          <el-form label-width="120px" :model="FormConcurrency"  :rules="rulesConcurrencyMode" ref="CaseRef">
            <el-form-item label="并发用户数：" prop="concurrencyNumber">
              <el-input v-model="FormConcurrency.concurrencyNumber"></el-input>
            </el-form-item>
            <el-form-item label="并发数步长：" prop="concurrencyStep">
              <el-input v-model="FormConcurrency.concurrencyStep"></el-input>
            </el-form-item>
            <el-form-item label="持续时长：" prop="lastLong">
              <el-input v-model="FormConcurrency.lastLong"></el-input>
            </el-form-item>

          </el-form>
        </el-card>
        <el-card v-if="configForm.pressureMode==='20'" style="margin-left: 7px;margin-right: 4px;background-color: #f5f7f9" class="card" shadow="always">
                  <el-form label-width="125px" :model="FormLadder" :rules="rulesLadderMode" ref="CaseRef">
                    <div v-for="(ladder, index) in FormLadder.ladders" :key="index">
                      <div style="color: #606266; display: flex; align-items: center; justify-content: space-between;">
                        <span>阶梯{{ index + 1 }}</span>
                        <el-button
                          :disabled="index < 1"
                          size="mini"
                          type="text"
                          @click="removeLadder(index)"
                        >
                          删除
                        </el-button>
                      </div>
                      <el-form-item label="并发用户数：" :prop="'ladders.' + index + '.concurrencyNumber'">
                        <el-input v-model="ladder.concurrencyNumber"></el-input>
                      </el-form-item>
                      <el-form-item label="并发数步长：" :prop="'ladders.' + index + '.concurrencyStep'">
                        <el-input v-model="ladder.concurrencyStep"></el-input>
                      </el-form-item>
                      <el-form-item label="阶梯持续时长：" :prop="'ladders.' + index + '.lastLong'">
                        <el-input v-model="ladder.lastLong"></el-input>
                      </el-form-item>
                    </div>
                  </el-form>
                  <el-button  style="width: 100%;margin-top: 20px; background-color: #ecf5ff; color: #409eff;" @click="addLadder" >
                    add Data
                  </el-button>
                </el-card>
      </el-form>
    </el-scrollbar>
  </el-card>
  <!--导入预设配置弹窗-->
  <el-dialog title="导入预设配置" v-model="SettingDlg" destroy-on-close :before-close="handleClose" width="80%" top="10px">
    <makeSet :setButton="setButton" :taskType="configForm.taskType" :distributedMode="configForm.distributed_mode" @set-dlg="handleClose"  @set-data="handleSetData" ></makeSet>
  </el-dialog>
</template>

<script>
import {mapMutations, mapState} from "vuex";
import {ElNotification, ElMessage, ElLoading} from "element-plus";
import makeSet from './makeSet.vue'
import timerTaskCron from "@/components/common/timerTaskCron";
import { InfoFilled } from '@element-plus/icons-vue'

export default {
  components: {
    makeSet,
    timerTaskCron,
    InfoFilled
  },
  data() {
    return {
      taskTypeMap: {'10': '普通任务', '20': '定时任务'},
      cronVisible: false,
      configForm: {
        name: '',
        rule: '',
        taskType: '',
        logMode: '0',
        pressureMode: '10',
        timeUnit: 's',
        control: '20',
        resource: '10',
        pressureConfig: {},
        project: '',
        creator: '',
        thinkTimeType:'10',
        thinkTime:[0],
        distributed_mode: 'single', // 只读，从任务获取
        master_server: null,        // 自定义时使用
        worker_servers: [],         // 自定义时使用
      },
      FormConcurrency:{
          lastLong:'',
          concurrencyNumber:'',
          concurrencyStep:''
        },
      FormLadder: {
        ladders: [
          { concurrencyNumber: '', concurrencyStep: '', lastLong: '' }
        ]
      },
      rulesConfig: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        thinkTime: [{ required: true, message: '请输入思考时间', trigger: 'blur' }],
        master_server: [
          { 
            validator: (rule, value, callback) => {
              if (this.configForm.distributed_mode === 'distributed' && this.configForm.resource === '20') {
                if (!value) {
                  if (this.configForm.worker_servers && this.configForm.worker_servers.length > 0) {
                    callback(new Error('请选择主服务器'));
                  }
                } else if (this.configForm.worker_servers && this.configForm.worker_servers.includes(value)) {
                  callback(new Error('主服务器和工作服务器不能选择同一个'));
                }
              }
              callback();
            }, 
            trigger: 'change' 
          }
        ],
        worker_servers: [
          { 
            validator: (rule, value, callback) => {
              if (this.configForm.distributed_mode === 'distributed' && this.configForm.resource === '20') {
                if (!value || value.length === 0) {
                  if (this.configForm.master_server) {
                    callback(new Error('请选择工作服务器'));
                  }
                } else if (this.configForm.master_server && value.includes(this.configForm.master_server)) {
                  callback(new Error('主服务器和工作服务器不能选择同一个'));
                }
              }
              callback();
            }, 
            trigger: 'change' 
          }
        ]
      },
      rulesConcurrencyMode: {
        lastLong: [{ required: true, message: '请输入持续时长', trigger: 'blur' }],
        concurrencyNumber: [{ required: true, message: '请输入并发数', trigger: 'blur' }],
        concurrencyStep: [{ required: true, message: '请输入步长', trigger: 'blur' }]
      },
      SettingDlg: false,
      setButton: true,
      serverData: [], // 保留，用于主服务器和工作服务器选择
      rulesLadderMode: {},
    }
  },
  computed: {
    ...mapState({
      ...mapState(['perfTask']),
      server: state => state.server,
      pro: state => state.pro
    }),
    username() {
      return window.sessionStorage.getItem('username');
    },
    selectedLogMode: {
      get() {
        return this.configForm.logMode.toString();
      },
      set(value) {
        this.configForm.logMode = Number(value);
      }
    },
    selectPressureMode: {
      get() {
        return this.configForm.pressureMode.toString();
      },
      set(value) {
        this.configForm.pressureMode = value;
      }
    },
    selectControlMode: {
      get() {
        return this.configForm.control.toString();
      },
      set(value) {
        this.configForm.control = Number(value);
      }
    },
    selectTimeType: {
      get() {
        return this.configForm.thinkTimeType.toString();
      },
      set(value) {
        this.configForm.thinkTimeType = value;
      }
     },

  },
  mounted() {
    this.configForm.taskType = this.perfTask.taskType;
    // 运行模式已在 created 中设置，这里不需要重复设置
    this.setRules();
    // 服务器数据已在 created 中加载，这里不需要重复加载
  },
  watch: {
    'configForm.thinkTimeType'(newType) {
      if (newType === '20') {
        this.configForm.thinkTime = [this.configForm.thinkTime[0], this.configForm.thinkTime[1]];
      } else {
        this.configForm.thinkTime = [this.configForm.thinkTime[0]];
      }
    }
  },
  methods: {
    handleClose(done) {
      if (done) {
        this.SettingDlg = false;
      } else {
        this.SettingDlg = false;
      }
    },

    handleSetData(data) {
      console.log('处理配置数据:', data);
      
      // 保留原有的运行模式，避免被覆盖
      const originalDistributedMode = this.configForm.distributed_mode;
      console.log('导入前运行模式:', originalDistributedMode);
      
      // 合并数据，但保留运行模式和必要的字段
      this.configForm = { 
        ...this.configForm, // 保留现有配置
        ...data, // 覆盖导入的数据
        distributed_mode: originalDistributedMode // 强制保留运行模式
      };
      console.log('导入后运行模式:', this.configForm.distributed_mode);
      
      // 确保 resource 字段有值
      if (!this.configForm.resource) {
        this.configForm.resource = '10';
        console.log('设置默认 resource 值:', this.configForm.resource);
      }
      
      // 处理分布式模式下的服务器配置
      if (this.configForm.distributed_mode === 'distributed') {
        if (data.master_server || (data.worker_servers && data.worker_servers.length > 0)) {
          // 有自定义服务器配置，设置为自定义模式
          this.configForm.resource = '20';
          this.configForm.master_server = data.master_server || null;
          this.configForm.worker_servers = data.worker_servers || [];
          console.log('设置为分布式自定义模式');
        } else {
          // 没有自定义服务器配置，设置为默认模式
          this.configForm.resource = '10';
          this.configForm.master_server = null;
          this.configForm.worker_servers = [];
          console.log('设置为分布式默认模式');
        }
      } else if (this.configForm.distributed_mode === 'single') {
        // 单机模式下清空服务器选择
        this.configForm.resource = '10';
        this.configForm.master_server = null;
        this.configForm.worker_servers = [];
        console.log('设置为单机模式');
      }
      
      // 处理压测配置
      if (this.configForm.pressureMode === '10') {
        this.FormConcurrency = data.pressureConfig || {};
      } else if (this.configForm.pressureMode === '20') {
        this.FormLadder = data.pressureConfig || { ladders: [{ concurrencyNumber: '', concurrencyStep: '', lastLong: '' }] };
      }
      
      console.log('配置数据更新完成:', this.configForm);
    },

    async getPresetting() {
     // 先确保服务器数据已加载
     if (this.serverData.length === 0) {
       await this.getServerData();
     }
     
     try {
       const response = await this.$api.getPresetting({
         project_id: this.pro.id,
         isSetting: true,
         task: this.perfTask.id
       });
       
       if (response.status === 200) {
         if (response.data.result && response.data.result.length > 0) {
           this.handleSetData(response.data.result[0]);
         } else {
           console.log('未找到任务配置数据');
         }
       }
     } catch (error) {
       console.error('获取任务配置失败:', error);
       this.$message.error('获取任务配置失败');
     }
    },

    clickResource(type) {
      if (type==='20') {
        // 自定义模式，用户需要手动选择服务器
      }
      else if (type==='10') {
        // 默认模式，清空自定义服务器选择
        this.configForm.master_server = null;
        this.configForm.worker_servers = [];
      }
      else {
        this.$message({
          message: '暂不支持该类型',
          type: 'warning'
        })
      }
    },

    clickSetting() {
      this.SettingDlg = true;
    },

    cronFun() {
      this.cronVisible = true;
    },
    closeRunTimeCron(isClose) {
      this.cronVisible = isClose;
    },
    runTimeCron(cron) {
      this.configForm.rule = cron;
    },

    async getServerData() {
      try {
        const response = await this.$api.getServers(this.pro.id, 1);
        if (response.status === 200) {
          this.serverData = response.data.result;
        }
      } catch (error) {
        console.error('加载服务器列表失败:', error);
        this.$message.error('加载服务器列表失败');
      }
    },
    dataSubmit() {
      const params = {...this.configForm}
      params.task = this.perfTask.id;
      params.update_time = this.$tools.newTime();
      params.modifier = this.username;
      params.creator = this.username;
      delete params.create_time;
      delete params.id;
      if (params.taskType === '10') delete params.rule;

      if (params.pressureMode === '10') {
        params.pressureConfig = this.FormConcurrency;
        const { ladders, ...rest } = params.pressureConfig;
        params.pressureConfig = rest;
      } else if (params.pressureMode === '20') {
        params.pressureConfig = this.FormLadder;
        const { ...rest } = params.pressureConfig;
        params.pressureConfig = rest;
      }
      params.project = this.pro.id;

      return params;
    },

    async clickSetEdit() {
      // 添加调试信息
      console.log('开始保存配置，当前 configForm 状态:', JSON.stringify(this.configForm, null, 2));
      console.log('resource 字段值:', this.configForm.resource);
      console.log('distributed_mode 字段值:', this.configForm.distributed_mode);
      
      // 先校验必填项
      const validationResult = this.validateRequiredFields();
      if (!validationResult.isValid) {
        console.log('验证失败，错误信息:', validationResult.errors);
        this.$message({
          type: 'warning',
          message: `请完善以下必填项：\n${validationResult.errors.join('\n')}`,
          duration: 4000
        });
        return;
      }

      // 显示加载状态
      const loading = this.$loading({
        lock: true,
        text: '正在保存任务配置...',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      try {
        // 表单验证
        const valid = await this.$refs.ConfigRef.validate();
        if (!valid) {
          loading.close();
          return;
        }

        // 构建保存参数
        const params = { ...this.configForm };
        
        // 根据运行模式处理服务器配置
        if (params.distributed_mode === 'distributed') {
          if (params.resource === '10') {
            // 默认模式，清空自定义服务器参数
            params.master_server = null;
            params.worker_servers = [];
          }
          // 自定义模式，保留传递的master_server和worker_servers参数
        } else {
          // 单机模式，清空服务器参数，但保留 resource 字段
          params.master_server = null;
          params.worker_servers = [];
          params.resource = '10'; // 单机模式使用默认值
        }

        // 验证关键配置 - 如果有问题直接返回，不保存
        const configValidationResult = this.validateTaskConfiguration(params);
        if (!configValidationResult.isValid) {
          loading.close();
          this.$message({
            type: 'warning',
            message: `配置验证失败：\n${configValidationResult.errors.join('\n')}`,
            duration: 4000
          });
          return;
        }

        console.log('开始保存配置，当前配置ID:', this.configForm.id);
        console.log('任务ID:', this.perfTask.id);
        console.log('项目ID:', this.pro.id);

        // 执行保存
        await this.performSave(params, loading);

      } catch (error) {
        loading.close();
        console.error('保存配置时发生错误:', error);
        this.$message({
          type: 'error',
          message: '保存失败: ' + (error.response?.data?.message || error.message || '未知错误'),
          duration: 3000
        });
      }
    },

    // 校验必填项
    validateRequiredFields() {
      const errors = [];
      let isValid = true;

      // 检查配置名称
      if (!this.configForm.name || this.configForm.name.trim() === '') {
        errors.push('• 配置名称不能为空');
        isValid = false;
      }

      // 检查 resource 字段
      if (!this.configForm.resource) {
        errors.push('• 资源模式不能为空');
        isValid = false;
      }

      // 检查分布式模式下的服务器配置
      if (this.configForm.distributed_mode === 'distributed') {
        if (this.configForm.resource === '20') {
          if (!this.configForm.master_server) {
            errors.push('• 分布式自定义模式下必须选择主服务器');
            isValid = false;
          }
          if (!this.configForm.worker_servers || this.configForm.worker_servers.length === 0) {
            errors.push('• 分布式自定义模式下必须选择至少一个工作服务器');
            isValid = false;
          }
        }
      }

      // 检查压测配置
      if (this.configForm.pressureMode === '10') {
        // 并发模式必填项检查
        if (!this.FormConcurrency.lastLong || this.FormConcurrency.lastLong.trim() === '') {
          errors.push('• 并发模式下必须设置持续时长');
          isValid = false;
        }
        if (!this.FormConcurrency.concurrencyNumber || this.FormConcurrency.concurrencyNumber.trim() === '') {
          errors.push('• 并发模式下必须设置并发用户数');
          isValid = false;
        }
        if (!this.FormConcurrency.concurrencyStep || this.FormConcurrency.concurrencyStep.trim() === '') {
          errors.push('• 并发模式下必须设置并发数步长');
          isValid = false;
        }
      } else if (this.configForm.pressureMode === '20') {
        // 阶梯模式必填项检查
        if (!this.FormLadder.ladders || this.FormLadder.ladders.length === 0) {
          errors.push('• 阶梯模式下必须配置阶梯参数');
          isValid = false;
        } else {
          // 检查每个阶梯的必填项
          this.FormLadder.ladders.forEach((ladder, index) => {
            if (!ladder.concurrencyNumber || ladder.concurrencyNumber.trim() === '') {
              errors.push(`• 阶梯${index + 1}的并发用户数不能为空`);
              isValid = false;
            }
            if (!ladder.concurrencyStep || ladder.concurrencyStep.trim() === '') {
              errors.push(`• 阶梯${index + 1}的并发数步长不能为空`);
              isValid = false;
            }
            if (!ladder.lastLong || ladder.lastLong.trim() === '') {
              errors.push(`• 阶梯${index + 1}的持续时长不能为空`);
              isValid = false;
            }
          });
        }
      }

      // 检查思考时间配置
      if (this.configForm.thinkTimeType === '10') {
        // 固定思考时间 - 允许为0
        if (!this.configForm.thinkTime || this.configForm.thinkTime.length === 0 || 
            this.configForm.thinkTime[0] === null || this.configForm.thinkTime[0] === undefined || 
            this.configForm.thinkTime[0].toString().trim() === '') {
          errors.push('• 固定思考时间不能为空');
          isValid = false;
        }
      } else if (this.configForm.thinkTimeType === '20') {
        // 随机思考时间
        if (!this.configForm.thinkTime || this.configForm.thinkTime.length < 2 || 
            this.configForm.thinkTime[0] === null || this.configForm.thinkTime[0] === undefined ||
            this.configForm.thinkTime[1] === null || this.configForm.thinkTime[1] === undefined ||
            this.configForm.thinkTime[0].toString().trim() === '' || 
            this.configForm.thinkTime[1].toString().trim() === '') {
          errors.push('• 随机思考时间的最小值和最大值不能为空');
          isValid = false;
        }
      }

      return { isValid, errors };
    },

    // 验证任务配置
    validateTaskConfiguration(params) {
      const errors = [];
      let isValid = true;

      // 检查配置名称
      if (!params.name || params.name.trim() === '') {
        errors.push('• 配置名称不能为空');
        isValid = false;
      }

      // 检查 resource 字段
      if (!params.resource) {
        errors.push('• 资源模式不能为空');
        isValid = false;
      }

      // 检查分布式模式下的服务器配置
      if (params.distributed_mode === 'distributed') {
        if (params.resource === '20') {
          if (!params.master_server) {
            errors.push('• 分布式自定义模式下必须选择主服务器');
            isValid = false;
          }
          if (!params.worker_servers || params.worker_servers.length === 0) {
            errors.push('• 分布式自定义模式下必须选择至少一个工作服务器');
            isValid = false;
          }
        }
      }

      // 检查压测配置
      if (params.pressureMode === '10') {
        // 并发模式检查
        if (!this.FormConcurrency.lastLong || this.FormConcurrency.lastLong.trim() === '') {
          errors.push('• 并发模式下必须设置持续时长');
          isValid = false;
        }
        if (!this.FormConcurrency.concurrencyNumber || this.FormConcurrency.concurrencyNumber.trim() === '') {
          errors.push('• 并发模式下必须设置并发用户数');
          isValid = false;
        }
        if (!this.FormConcurrency.concurrencyStep || this.FormConcurrency.concurrencyStep.trim() === '') {
          errors.push('• 并发模式下必须设置并发数步长');
          isValid = false;
        }
      } else if (params.pressureMode === '20') {
        // 阶梯模式检查
        if (!this.FormLadder.ladders || this.FormLadder.ladders.length === 0) {
          errors.push('• 阶梯模式下必须配置阶梯参数');
          isValid = false;
        } else {
          // 检查每个阶梯的必填项
          this.FormLadder.ladders.forEach((ladder, index) => {
            if (!ladder.concurrencyNumber || ladder.concurrencyNumber.trim() === '') {
              errors.push(`• 阶梯${index + 1}的并发用户数不能为空`);
              isValid = false;
            }
            if (!ladder.concurrencyStep || ladder.concurrencyStep.trim() === '') {
              errors.push(`• 阶梯${index + 1}的并发数步长不能为空`);
              isValid = false;
            }
            if (!ladder.lastLong || ladder.lastLong.trim() === '') {
              errors.push(`• 阶梯${index + 1}的持续时长不能为空`);
              isValid = false;
            }
          });
        }
      }

      return { isValid, errors };
    },

    // 执行保存操作
    async performSave(params, loading) {
      try {
        // 构建完整的保存参数
        const saveParams = this.buildSaveParams(params);
        
        console.log('使用save_presetting方法保存配置');
        
        // 使用save_presetting方法，这个方法会自动处理创建或更新
        const response = await this.$api.setPresetting(saveParams);
        
        if (response.status === 200) {
          loading.close();
          
          // 显示成功通知
          ElNotification({
            title: '配置保存成功',
            message: `任务配置"${saveParams.name}"已成功保存`,
            type: 'success',
            duration: 3000,
            showClose: true,
            position: 'top-right',
          });

          // 更新本地配置数据
          this.configForm = { ...response.data };
          
          // 重新获取配置数据以确保数据同步
          await this.getPresetting();
          
          // 触发父组件更新
          this.$emit('config-saved', response.data);
          
        } else {
          throw new Error('保存失败，请重试');
        }
      } catch (error) {
        loading.close();
        console.error('保存配置失败:', error);
        
        // 显示详细错误信息
        let errorMessage = '配置保存失败';
        if (error.response?.data?.message) {
          errorMessage += ': ' + error.response.data.message;
        } else if (error.response?.data?.detail) {
          errorMessage += ': ' + error.response.data.detail;
        } else if (error.message) {
          errorMessage += ': ' + error.message;
        }
        
        ElMessage({
          type: 'error',
          message: errorMessage,
          duration: 4000
        });
      }
    },

    // 构建保存参数
    buildSaveParams(params) {
      const saveParams = { ...params };
      
      console.log('开始构建保存参数，原始参数:', params);
      
      // 添加必要的字段
      saveParams.task = this.perfTask.id;
      saveParams.project = this.pro.id;
      saveParams.isSetting = true;
      saveParams.update_time = this.$tools.newTime();
      saveParams.modifier = this.username;
      saveParams.creator = this.username;
      
      console.log('添加基础字段后:', saveParams);
      
      // 处理压测配置
      if (saveParams.pressureMode === '10') {
        // 并发模式
        saveParams.pressureConfig = {
          concurrencyNumber: this.FormConcurrency.concurrencyNumber,
          concurrencyStep: this.FormConcurrency.concurrencyStep,
          lastLong: this.FormConcurrency.lastLong
        };
        console.log('并发模式压测配置:', saveParams.pressureConfig);
      } else if (saveParams.pressureMode === '20') {
        // 阶梯模式
        saveParams.pressureConfig = {
          ladders: this.FormLadder.ladders.map(ladder => ({
            concurrencyNumber: ladder.concurrencyNumber,
            concurrencyStep: ladder.concurrencyStep,
            lastLong: ladder.lastLong
          }))
        };
        console.log('阶梯模式压测配置:', saveParams.pressureConfig);
      }
      
      // 处理思考时间
      if (saveParams.thinkTimeType === '10') {
        // 固定思考时间
        saveParams.thinkTime = [this.configForm.thinkTime[0]];
      } else if (saveParams.thinkTimeType === '20') {
        // 随机思考时间
        saveParams.thinkTime = [this.configForm.thinkTime[0], this.configForm.thinkTime[1]];
      }
      console.log('思考时间配置:', saveParams.thinkTime);
      
      // 处理分布式模式配置
      if (saveParams.distributed_mode === 'single') {
        // 单机模式，清空服务器配置，但保留 resource 字段
        saveParams.master_server = null;
        saveParams.worker_servers = [];
        saveParams.resource = '10'; // 单机模式使用默认值
        console.log('单机模式，清空服务器配置，设置默认resource');
      } else if (saveParams.distributed_mode === 'distributed') {
        if (saveParams.resource === '10') {
          // 默认模式，清空自定义服务器参数，使用任务初始配置
          saveParams.master_server = null;
          saveParams.worker_servers = [];
          console.log('分布式默认模式，清空自定义服务器配置');
        } else if (saveParams.resource === '20') {
          // 自定义模式，保留服务器配置
          console.log('分布式自定义模式，保留服务器配置:', {
            master_server: saveParams.master_server,
            worker_servers: saveParams.worker_servers
          });
        }
      }
      
      // 处理定时任务规则
      if (saveParams.taskType === '10') {
        delete saveParams.rule;
        console.log('普通任务，删除定时规则');
      }
      
      // 最终检查：确保 resource 字段有值
      if (!saveParams.resource) {
        console.warn('resource 字段为空，设置为默认值');
        saveParams.resource = '10';
      }
      
      console.log('最终构建的保存参数:', saveParams);
      return saveParams;
    },

    addLadder() {
      this.FormLadder.ladders.push({
        concurrencyNumber: '',
        concurrencyStep: '',
        lastLong: ''
      });
      this.setRules()
    },

    setRules() {
      // 动态生成验证规则
      const ladderRules = {};
      // 遍历 FormLadder.ladders 数组，为每个阶梯项动态设置规则
      this.FormLadder.ladders.forEach((_, index) => {
        ladderRules[`ladders.${index}.concurrencyNumber`] = [
          { required: true, message: '并发用户数不能为空', trigger: 'blur' },
        ];
        ladderRules[`ladders.${index}.concurrencyStep`] = [
          { required: true, message: '并发数步长不能为空', trigger: 'blur' },
        ];
        ladderRules[`ladders.${index}.lastLong`] = [
          { required: true, message: '阶梯持续时长不能为空', trigger: 'blur' },
        ];
      });

      // 设置 rulesLadderMode 的值
      this.rulesLadderMode = ladderRules;
    },

    removeLadder(index) {
      if (this.FormLadder.ladders.length > 1) {
        this.FormLadder.ladders.splice(index, 1);
        this.setRules();
      }
    },





    onResourceChange() {
      if (this.configForm.resource === '10') {
        // 切换到默认，清空自定义服务器
        this.configForm.master_server = null;
        this.configForm.worker_servers = [];
      }
      // 切换到自定义，不做处理
    },

  },
  async created() {
    await this.getServerData();
    // 先设置运行模式，再获取预设配置
    this.configForm.distributed_mode = this.perfTask.distributed_mode;
    // 确保 resource 字段有默认值
    if (!this.configForm.resource) {
      this.configForm.resource = '10'; // 默认使用默认模式
    }
    console.log('任务运行模式:', this.perfTask.distributed_mode);
    console.log('设置后运行模式:', this.configForm.distributed_mode);
    console.log('初始 resource 值:', this.configForm.resource);
    console.log('初始 configForm:', JSON.stringify(this.configForm, null, 2));
    await this.getPresetting();
    console.log('获取预设配置后的 configForm:', JSON.stringify(this.configForm, null, 2));
  }
}
</script>

<style scoped>

:deep(.el-scrollbar__bar) {
  display: none;
}

/* 配置验证对话框样式 */
:deep(.config-validation-dialog) {
  .el-message-box {
    width: 500px !important;
  }

  .el-message-box__message {
    white-space: pre-line !important;
    line-height: 1.6 !important;
    text-align: left !important;
  }
}

/* 保存按钮样式优化 */
.el-button[type="primary"] {
  background: linear-gradient(to right, #409eff, #53a8ff);
  border: none;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
  transition: all 0.3s;
  font-weight: 500;
}

.el-button[type="primary"]:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  background: linear-gradient(to right, #53a8ff, #66b1ff);
}

.el-button[type="primary"]:active {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

/* 配置卡片样式 */
.el-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: none;
  transition: all 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 500;
  color: #303133;
}

/* 提示框样式 */
.tip-box {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 13px;
  margin-top: 8px;
}

.tip-box.info {
  background: #f0f9ff;
  color: #409eff;
  border-left: 3px solid #409eff;
}

.tip-box.warning {
  background: #fff7e6;
  color: #e6a23c;
  border-left: 3px solid #e6a23c;
}

/* 加载状态样式 */
:deep(.el-loading-mask) {
  background-color: rgba(0, 0, 0, 0.7) !important;
}

:deep(.el-loading-spinner) {
  .el-loading-text {
    color: #ffffff;
    font-size: 14px;
    font-weight: 500;
  }
}

/* 通知样式优化 */
:deep(.el-notification) {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-notification--success) {
  background: linear-gradient(to right, #67c23a, #85ce61);
  border-left: 4px solid #67c23a;
}

:deep(.el-notification--error) {
  background: linear-gradient(to right, #f56c6c, #f78989);
  border-left: 4px solid #f56c6c;
}

</style>